﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace XCommunity.Forums.Extension
{
  public class CachedCounter : IFormattable
  {


    private int _seed;

    /// <summary>
    /// 创建一个缓存的计数器
    /// </summary>
    /// <param name="seed">计数器种子</param>
    public CachedCounter( int seed )
    {
      _seed = seed;
    }

    private int _increment;


    /// <summary>
    /// 计数值
    /// </summary>
    public int Count
    {
      get { return _seed + _increment; }
    }


    /// <summary>
    /// 增量
    /// </summary>
    public int Increment
    {
      get { return _increment; }
    }


    /// <summary>
    /// 重设计数器并返回增量
    /// </summary>
    /// <returns>增量</returns>
    public int Reset()
    {
      lock ( this )
      {
        int value = _increment;
        _increment = 0;
        _seed += value;
        return value;
      }
    }



    public static implicit operator int( CachedCounter counter )
    {
      return counter.Count;
    }

    public static CachedCounter operator ++( CachedCounter counter )
    {
      counter._increment++;
      return counter;
    }

    public override string ToString()
    {
      return Count.ToString();
    }


    #region IFormattable 成员

    string IFormattable.ToString( string format, IFormatProvider formatProvider )
    {
      return Count.ToString( format, formatProvider );
    }

    #endregion
  }
}
